<?php
namespace app\index\controller;

use app\index\model\Activity;

use app\index\model\Order;

use app\index\model\Reward;
use app\index\model\User;
use app\index\service\WechatPay;
use app\lib\exception\RewardException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UploadImgException;
use app\lib\exception\ActivityException;
use app\lib\validate\ActivityValidate;
use app\index\service\Share;


use app\lib\validate\IDMustBePostiveInt;

use think\Request;

class Index extends Base
{
    //首页
    public function index()
    {
        return 'index';
        $list = Activity::where("status", "=", 1)->with(["wxuser"])->select();
        $user = User::where("id",session("uid"))->with(["wxuser"])->find();
        $this->assign('list', $list);
        $this->assign('user', $user);
        return view();
    }
    //添加活动页面
    public function add()
    {
        return view();
    }
    //添加活动行为
    public function addActivity()
    {
        (new ActivityValidate())->goCheck();
        $postData = request()->post();
        if($postData['all_money_num']/$postData['person'] < 1){
            throw new ActivityException([
                'msg' => '每个红包金额必须大于一元',
            ]);
        }

        $postData['uid'] = session('uid');
        $postData['status'] = 0;//未审核
        $res = Activity::create($postData, true);
        $order_id = $this->addOrder($res);
        throw new SuccessMessage([
            'msg' => url('My/dopay', ['id' => $order_id]),
        ]);
    }
    //领红包页面
    public function reward($id)
    {
        (new IDMustBePostiveInt())->goCheck();
        $list = Activity::where("id", "=", $id)->with(["reward","reward.user","reward.user.wxuser"])->find();
        $list['is_reward'] = 1;
        $list['reward_count'] = count($list['reward']);//已经领取人数
        $list['reward_total'] = Reward::where("activity_id", $id)->where("uid", ">", 0)->sum("money"); //已经领取金额
        //判断是否已经领取
        $rewards = Reward::where("activity_id", $id)->where("uid", "=", session("uid"))->find();
        if ($rewards) {
            $list['is_reward'] = -1;
        } //已领取人数大于等于红包人数 不能领取
        elseif ($list['reward_count']>= $list['person']) {
            $list['is_reward'] = 0;
        }
        //微信分享
        //$wxData = Share::WechatShare();
        //$this->assign('wxData',$wxData);
        $this->assign('list', $list);
        return view();
    }

    /** //领红包行为
     * @param $id activity_id
     * @throws RewardException
     * @throws SuccessMessage
     * @throws \app\lib\exception\ParameterException
     * @throws \think\Exception
     */
    public function getReward($id)
    {
        (new IDMustBePostiveInt())->goCheck();
        //已经领取人数
        $reward_num = Reward::where('activity_id', "=", $id)->where("uid", ">", 0)->count();
        $data = Activity::where("id", "=", $id)->field(["all_money_num","person"])->find();

        if ($data['all_money_num'] == 0 || $data['person'] == 0) {
            throw new RewardException([
                'msg' => '红包金额或人数为零'
            ]);
        }
        if ($reward_num >= $data['person']) {
            throw new RewardException([
               'msg' => '红包已领完'
            ]);
        }
        //记录领取人，
        $rewardObj = Reward::where('activity_id', "=", $id)->where("uid", "=", 0)->find();
        $rewardObj->uid = session("uid");
        $rewardObj->order_no = getOrderNo();
        $res = $rewardObj->save();
        
        //$rewardObj = Reward::update(["uid" => $uid,"order_no" => getOrderNo()],["id"=>$rewardData["id"]]);
        //更新用户表
        User::where('id', "=", $rewardObj->uid)->setInc("money", $rewardObj->money);
        //最后一个红包
        if (count($rewardObj) == 1) {
            $list = Reward::where('activity_id', "=", $id)->where("uid", ">", 0)->with(["wxuser"])->select();
            foreach ($list as $val) {
                $ret = $this->sendRedPack($val['money'], $val['order_no'], $val['wxuser']['openid'], $val['id']);
            }
        }
        throw new SuccessMessage([
            'msg'=> '红包领取成功，您可以分享给朋友一起来领哦'
            ]);
    }
     //发红包
    private function sendRedPack($money, $orderNo, $openid, $order_id)
    {
         $res = WechatPay::makeWxRedPack($money, $orderNo, $openid);
            // $res = "<xml>
            //         <return_code><![CDATA[SUCCESS]]></return_code>
            //         <return_msg><![CDATA[发放成功]]></return_msg>
            //         <result_code><![CDATA[SUCCESS]]></result_code>
            //         <err_code><![CDATA[SUCCESS]]></err_code>
            //         <err_code_des><![CDATA[发放成功]]></err_code_des>
            //         <mch_billno><![CDATA[1801101145473331]]></mch_billno>
            //         <mch_id><![CDATA[1486194362]]></mch_id>
            //         <wxappid><![CDATA[wx79972369da52d8bd]]></wxappid>
            //         <re_openid><![CDATA[oxjZG1Svckge--VJFkYL_-ReUhwY]]></re_openid>
            //         <total_amount>100</total_amount>
            //         <send_listid><![CDATA[1000041701201801103000089669301]]></send_listid>
            //         </xml>";
            $notifyInfo = (array) simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);
           
        if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
            //修改状态
            return Reward::update(["status" => 1], ["id"=>$order_id]);
        } else {
            $notifyInfo['uid'] = Reward::get($order_id)['uid'];
            LogWrite($notifyInfo);
            return false;
        }
    }



    //新增订单
    private function addOrder($activity)
    {
        $data['orderNo'] =  getOrderNo();
        $data['money'] =  $activity->all_money_num;
        $data['status'] =  1;//未支付
        $data['uid'] =  session('uid');
        $data['activity_id'] =  $activity->id;
        $res = Order::create($data, true);
        return $res->id;
    }

    public function test()
    {
        // $filename = '收款交易下载%282018-01-01至2018-01-31%29.xls';
        // $time = substr(strstr($filename,'20'),0,23);
 
         
        for ($i = 1; $i <= 10; $i++) {
            p ($i);
        }
    }


    //图片上传
    public function uploadImg()
    {
        $file = request()->file('imgFile');
        // 移动到框架应用根目录/public/uploads/ 目录下 上传图片2M以内
        $info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            $dir =   '/uploads/'.$info->getSaveName();
            throw new SuccessMessage([
                'msg' => '上传成功',
                'data'=>$dir,
            ]);
        } else {
            // 上传失败获取错误信息
            throw new UploadImgException([
               'msg' =>$file->getError()
            ]);
        }
    }
}
